// -----------------------------------------------------------------------------
// This source file is part of Matrix Platform
// 	(Universal .NET Software Development Platform)
// For the latest info, see http://www.matrixplatform.com
// 
// Copyright (c) 2009-2010, Ingenious Ltd
// 
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// 
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
// 
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
// -----------------------------------------------------------------------------
using System;
using System.Windows.Forms;
using Matrix.Common.Diagnostics.TracerCore.Filters;
using Matrix.Common.Extended;
using Matrix.Common.FrontEnd;

namespace Matrix.Common.Diagnostics.FrontEnd.TracerControls
{
    /// <summary>
    /// Control allows controlling the originating baseMethod based filtering of tracer items.
    /// </summary>
    public partial class MethodTracerFilterControl : UserControl
    {
        MethodTracerFilter _filter;
        /// <summary>
        /// The filter instance associated with this control.
        /// </summary>
        public MethodTracerFilter Filter
        {
            get { return _filter; }
            set 
            {
                if (_filter != null)
                {
                    _filter.FilterUpdatedEvent -= new TracerFilter.FilterUpdatedDelegate(_filter_FilterUpdatedEvent);
                    _filter = null;
                }

                _filter = value;

                if (_filter != null)
                {
                    _filter.FilterUpdatedEvent += new TracerFilter.FilterUpdatedDelegate(_filter_FilterUpdatedEvent);
                }

                UpdateUI();

                treeView.ExpandAll();
            }
        }

       
        /// <summary>
        /// 
        /// </summary>
        public MethodTracerFilterControl()
        {
            InitializeComponent();
        }

        /// <summary>
        /// Possible NON UI thread.
        /// </summary>
        void _filter_FilterUpdatedEvent(TracerFilter filter)
        {
            WinFormsHelper.BeginManagedInvoke(this, new GeneralHelper.DefaultDelegate(UpdateUI));
        }

        /// <summary>
        /// Update user interface based on the underlying information.
        /// </summary>
        void UpdateUI()
        {
            if (_filter == null)
            {
                treeView.Nodes.Clear();
                return;
            }

            int i = 0;
            lock (_filter)
            {
                foreach (string assemblyName in _filter.Assemblies)
                {
                    if (i > treeView.Nodes.Count - 1)
                    {
                        treeView.Nodes.Add("New node");
                    }

                    SetNodeToAssembly(treeView.Nodes[i], assemblyName);
                    i++;
                }
            }
            
            // Clear remaining nodes.
            for (int j = treeView.Nodes.Count - 1; j >= i; j--)
            {
                treeView.Nodes.RemoveAt(j);
            }
        }

        void SetNodeToType(TreeNode node, string assemblyName, string typeName)
        {
            node.Tag = typeName + "|" + assemblyName;
            node.Text = typeName + " Class";

            lock (_filter)
            {
                node.Checked = _filter.GetAssemblyInfo(assemblyName).TypesNames[typeName];
            }
        }

        void SetNodeToAssembly(TreeNode assemblyNode, string assemblyName)
        {
            assemblyNode.Tag = assemblyName;
            assemblyNode.Text = assemblyName;

            lock (_filter)
            {
                assemblyNode.Checked = _filter.GetAssemblyInfo(assemblyName).Enabled;

                int i = 0;
                foreach (string typeName in _filter.GetAssemblyInfo(assemblyName).TypesNames.Keys)
                {
                    if (i > assemblyNode.Nodes.Count - 1)
                    {
                        assemblyNode.Nodes.Add("New node");
                    }

                    SetNodeToType(assemblyNode.Nodes[i], assemblyName, typeName);
                    i++;
                }

                // Clear remaining nodes.
                for (int j = assemblyNode.Nodes.Count - 1; j >= i; j--)
                {
                    assemblyNode.Nodes.RemoveAt(j);
                }
            }
        }


        private void treeView_AfterCheck(object sender, TreeViewEventArgs e)
        {
            if (_filter == null)
            {
                return;
            }
            
            string tag = e.Node.Tag as string;
            if (string.IsNullOrEmpty(tag))
            {
                return;
            }

            lock (_filter)
            {
                if (tag.Contains("|") == false)
                {// Assembly.
                    string assemblyName = tag;
                    if (_filter.GetAssemblyInfo(assemblyName).Enabled != e.Node.Checked)
                    {// Protect when SetNodeToAssembly is called.
                        _filter.GetAssemblyInfo(assemblyName).Enabled = e.Node.Checked;
                    }
                }
                else if (e.Node.Tag is Type)
                {// Class.
                    string typeName = tag.Split('|')[0];
                    string assemblyName = tag.Split('|')[1];
                    if (_filter.GetAssemblyInfo(assemblyName).TypesNames[typeName] != e.Node.Checked)
                    {// Protect when SetNodeToType is called.
                        _filter.GetAssemblyInfo(assemblyName).TypesNames[typeName] = e.Node.Checked;
                    }
                }
                else
                {
                    throw new Exception("Unhandled type.");
                }
            }
        }

        private void toolStripButtonCheckAll_Click(object sender, EventArgs e)
        {
            foreach (TreeNode node in treeView.Nodes)
            {
                node.Checked = true;
            }
        }

        private void toolStripButtonUnCheckAll_Click(object sender, EventArgs e)
        {
            foreach (TreeNode node in treeView.Nodes)
            {
                node.Checked = false;
            }
        }

    }
}
